<?php

namespace App\Jobs;

use App\Models\AppealTask;
use App\Models\CapitalFlow;
use App\Models\MerchantCheckLog;
use App\Models\OrderRecord;
use App\Models\PushTask;
use App\Models\SaleAssess;
use App\Models\SalePlan;
use App\Models\SaleTask;
use App\Tools\Logs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ProcessDeleteData implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $data;

    private $task_ids = [];

    private $task_codes = [];

    private $plan_code;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->data = $data;
        $this->plan_code = $this->data['plan_code'];
        $this->task_ids = SaleTask::where('plan_code', $this->plan_code)->pluck('id');
        $this->task_codes = SaleTask::where('plan_code', $this->plan_code)->pluck('task_code');

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $t1 = microtime(true);
        $push_task_ids = [];

        DB::beginTransaction();
        try {
            // 删除刷手任务表数据
            $push_task_ids = PushTask::whereIn('task_id', $this->task_ids)->where('task_type', 1)->pluck('id');
            $pushTaskNum = 0;
            $pushTaskNum = PushTask::destroy($push_task_ids);

            // 删除销量任务表数据
            $saleTaskNum = 0;
            $saleTaskNum = SaleTask::destroy($this->task_ids);

            // 删除任务记录表数据
            $orderRecordId = OrderRecord::where('plan_type', 1)->whereIn('task_id', $this->task_ids)->pluck('id');
            $orderRecordNum = 0;
            $orderRecordNum = OrderRecord::destroy($orderRecordId);

            // 删除商户审核表数据
            $merchantCheckLogId = MerchantCheckLog::where('plan_type', 1)->whereIn('task_id', $this->task_ids)->pluck('id');
            $merchantCheckLogNum = 0;
            $merchantCheckLogNum = MerchantCheckLog::destroy($merchantCheckLogId);

            // 删除资金流水表数据
            $capitalFlowId = CapitalFlow::where('plan_type', 1)->whereIn('task_id', $this->task_ids)->pluck('id');
            $capitalFlowNum = 0;
            $capitalFlowNum = CapitalFlow::destroy($capitalFlowId);

            // 删除任务申诉表数据
            $appealTaskId = AppealTask::where('task_type', 1)->whereIn('task_code', $this->task_codes)->pluck('id');
            $appealTaskNum = 0;
            $appealTaskNum = AppealTask::destroy($appealTaskId);

            // 删除评论任务表数据
            $saleAssessId = SaleAssess::whereIn('task_code', $this->task_codes)->pluck('id');
            $saleAssessNum = 0;
            $saleAssessNum = SaleAssess::destroy($saleAssessId);

            // 删除计划
            SalePlan::destroy($this->data['id']);

            DB::commit();

            $t2 = microtime(true);

            // 记录删除的id，以便回滚
            if (!empty($push_task_ids)) Logs::info(implode(',', $push_task_ids->toArray()), [], 'push_task_ids');
            if (!empty($this->task_ids)) Logs::info(implode(',', $this->task_ids->toArray()), [], 'task_ids');
            if (!empty($orderRecordId)) Logs::info(implode(',', $orderRecordId->toArray()), [], 'order_record_ids');
            if (!empty($merchantCheckLogId)) Logs::info(implode(',', $merchantCheckLogId->toArray()), [], 'merchant_check_log_ids');
            if (!empty($capitalFlowId)) Logs::info(implode(',', $capitalFlowId->toArray()), [], 'capital_flow_ids');
            if (!empty($appealTaskId)) Logs::info(implode(',', $appealTaskId->toArray()), [], 'appeal_task_ids');
            if (!empty($saleAssessId)) Logs::info(implode(',', $saleAssessId->toArray()), [], 'sale_assess_ids');

            Logs::info("删除条件: ".json_encode([
                    'plan_code' => $this->plan_code,
                    'push_task_id' => $push_task_ids,
                    'task_id' => $this->task_ids,
                    'task_code' => $this->task_codes
                ]). "sale_task删除数量: {$saleTaskNum}, push_task删除数量: {$pushTaskNum},
            order_record删除数量: {$orderRecordNum}, appeal_task删除数量: {$appealTaskNum},
            merchant_check_log删除数量: {$merchantCheckLogNum}, capital_flow删除数量: {$capitalFlowNum},
            sale_assess删除数量：{$saleAssessNum}".
                "执行代码时长: ". round($t2-$t1,3). "秒", [], 'delete_'.date('Ymd'));

            // 释放订单共享锁
            $dispatch_task_id = json_decode(Redis::get("plan_code_list"), true);
            $dispatch_taskid_key = array_search($this->data['id'], $dispatch_task_id);
            array_splice($dispatch_task_id, $dispatch_taskid_key, 1);
            Redis::set("plan_code_list", json_encode($dispatch_task_id));
            return true;

        }catch (\Exception $exception) {
            $t2 = microtime(true);
            Logs::error("删除条件: ".json_encode([
                    'plan_code' => $this->plan_code,
                    'push_task_id' => $push_task_ids,
                    'task_id' => $this->task_ids,
                    'task_code' => $this->task_codes
                ]). ", 删除错误: ".$exception->getMessage(). ", 执行代码时长: ". round($t2-$t1,3). "秒", [], 'delete_'.date('Ymd'));
            DB::rollBack();

            // 释放订单共享锁
            $dispatch_task_id = json_decode(Redis::get("plan_code_list"), true);
            $dispatch_taskid_key = array_search($this->data['id'], $dispatch_task_id);
            array_splice($dispatch_task_id, $dispatch_taskid_key, 1);
            Redis::set("plan_code_list", json_encode($dispatch_task_id));
            return true;
        }
    }
}
